package com.jinzhi.jzapi.common.controller;

import com.jinzhi.jzapi.common.pojo.CerUtilsVo;
import com.jinzhi.jzapi.utils.CerSynthesisUtil;
import com.jinzhi.jzweb.domain.*;
import com.jinzhi.jzweb.domain.moduleConfig.CareStuSignUpComRealityDO;
import com.jinzhi.jzweb.service.*;
import com.jinzhi.jzweb.service.moduleConfig.CareStuSignUpComRealityService;
import com.jinzhi.jzweb.utils.ValuesUtil;
import net.sf.json.JSONArray;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class ApittController {

    @Autowired
    private TrainingCertificatesService trainingCertificatesService;
    @Autowired
    private ExaminationPaperService examinationPaperService;
    @Autowired
    private ExaminationBatchService examinationBatchService;
    @Autowired
    private StuSignUpComService stuSignUpService;
    @Autowired
    private ExaminationResultsComService examinationResultsService;
    @Autowired
    private ExaminationAnswerSheetComService examinationAnswerSheetService;
    @Autowired
    private ExaminationQuestionsService examinationQuestionsService;

    //幼儿照护
    @Async
    public void doTask11(List<CerUtilsVo> cerUtilsVos, List<TrainingCertificatesDO> traCerDOList){
        // 实现run方法
        for (int i = 0; i < cerUtilsVos.size(); i++) {
            //证书图片
            String cerImgUrl = null;
            String cerImgUrlNoSale = null;
            if (cerUtilsVos.get(i).getType() == 0) {
                try {
                    //参数说明：合成类型（0带公章，1不带公章），背景图，学员姓名，学员图像， 身份证号码，证书编码，考核期数，培训章节数（学时），培训年份，培训月份，培训日期，获证年份，获证年份，获证年份，电子公章
                    cerImgUrl = CerSynthesisUtil.overTrainingImage(0, cerUtilsVos.get(i).getBackgroundPath(), cerUtilsVos.get(i).getStuName(), cerUtilsVos.get(i).getStuImg(),
                            cerUtilsVos.get(i).getIdCard(), cerUtilsVos.get(i).getCerNumber(), cerUtilsVos.get(i).getNumPeriods(), cerUtilsVos.get(i).getTrainingNumber(),
                            cerUtilsVos.get(i).getTraYear(), cerUtilsVos.get(i).getTraMath(), cerUtilsVos.get(i).getTraDay(), cerUtilsVos.get(i).getCerYear(), cerUtilsVos.get(i).getCerMath(),
                            cerUtilsVos.get(i).getCerDay(), cerUtilsVos.get(i).getElectronicSeal(),cerUtilsVos.get(i).getWorkUnit(),cerUtilsVos.get(i).getGrade());
                    cerImgUrlNoSale = CerSynthesisUtil.overTrainingImage(1, cerUtilsVos.get(i).getBackgroundPath(), cerUtilsVos.get(i).getStuName(), cerUtilsVos.get(i).getStuImg(),
                            cerUtilsVos.get(i).getIdCard(), cerUtilsVos.get(i).getCerNumber(), cerUtilsVos.get(i).getNumPeriods(), cerUtilsVos.get(i).getTrainingNumber(),
                            cerUtilsVos.get(i).getTraYear(), cerUtilsVos.get(i).getTraMath(), cerUtilsVos.get(i).getTraDay(), cerUtilsVos.get(i).getCerYear(), cerUtilsVos.get(i).getCerMath(),
                            cerUtilsVos.get(i).getCerDay(), cerUtilsVos.get(i).getElectronicSeal(),cerUtilsVos.get(i).getWorkUnit(),cerUtilsVos.get(i).getGrade());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (cerUtilsVos.get(i).getType() == 1) {
                try {
                    //考评员证书
                    //参数说明：背景图，学员姓名，学员图像， 身份证号码，证书编码，证书名称，有效日期
                    cerImgUrl = CerSynthesisUtil.overTraExaImage(cerUtilsVos.get(i).getBackgroundPath(), cerUtilsVos.get(i).getStuName(), cerUtilsVos.get(i).getStuImg(),
                            cerUtilsVos.get(i).getIdCard(), cerUtilsVos.get(i).getCerNumber(), cerUtilsVos.get(i).getEffectiveDate(),cerUtilsVos.get(i).getWorkUnit(),cerUtilsVos.get(i).getGrade());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }else if (cerUtilsVos.get(i).getType() == 2) {
                try {
                    //考务技术员证书
                    //参数说明：背景图，学员姓名，学员图像， 身份证号码，证书编码，证书名称，有效日期
                    cerImgUrl = CerSynthesisUtil.overTraExaAffImage(cerUtilsVos.get(i).getBackgroundPath(), cerUtilsVos.get(i).getStuName(), cerUtilsVos.get(i).getStuImg(),
                            cerUtilsVos.get(i).getIdCard(), cerUtilsVos.get(i).getCerNumber(), cerUtilsVos.get(i).getEffectiveDate(),cerUtilsVos.get(i).getWorkUnit());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }else if (cerUtilsVos.get(i).getType() == 3) {
                try {
                	//考务技术员-结业证书
                    //参数说明：合成类型（0带公章，1不带公章），背景图，学员姓名，学员图像， 身份证号码，证书编码，考核期数，培训章节数（学时），培训年份，培训月份，培训日期，获证年份，获证年份，获证年份，电子公章
                    cerImgUrl = CerSynthesisUtil.overTraAraGradiningImage(0, cerUtilsVos.get(i).getBackgroundPath(), cerUtilsVos.get(i).getStuName(), cerUtilsVos.get(i).getStuImg(),
                            cerUtilsVos.get(i).getIdCard(), cerUtilsVos.get(i).getCerNumber(), cerUtilsVos.get(i).getNumPeriods(), cerUtilsVos.get(i).getTrainingNumber(),
                            cerUtilsVos.get(i).getTraYear(), cerUtilsVos.get(i).getTraMath(), cerUtilsVos.get(i).getTraDay(), cerUtilsVos.get(i).getCerYear(), cerUtilsVos.get(i).getCerMath(),
                            cerUtilsVos.get(i).getCerDay(), cerUtilsVos.get(i).getElectronicSeal(),cerUtilsVos.get(i).getWorkUnit());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } 
            else if (cerUtilsVos.get(i).getType() == 4) {
                try {
                    //督导员证
                    //参数说明：背景图，学员姓名，学员图像， 身份证号码，证书编码，证书名称，有效日期
                    cerImgUrl = CerSynthesisUtil.overTraSupervisorExaAffImage(cerUtilsVos.get(i).getBackgroundPath(), cerUtilsVos.get(i).getStuName(), cerUtilsVos.get(i).getStuImg(),
                            cerUtilsVos.get(i).getIdCard(), cerUtilsVos.get(i).getCerNumber(), cerUtilsVos.get(i).getEffectiveDate(),cerUtilsVos.get(i).getWorkUnit());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }else if (cerUtilsVos.get(i).getType() == 5) {
                try {
                	//督导员-结业证书
                    //参数说明：合成类型（0带公章，1不带公章），背景图，学员姓名，学员图像， 身份证号码，证书编码，考核期数，培训章节数（学时），培训年份，培训月份，培训日期，获证年份，获证年份，获证年份，电子公章
                    cerImgUrl = CerSynthesisUtil.overTraSupervisorGradiningImage(0, cerUtilsVos.get(i).getBackgroundPath(), cerUtilsVos.get(i).getStuName(), cerUtilsVos.get(i).getStuImg(),
                            cerUtilsVos.get(i).getIdCard(), cerUtilsVos.get(i).getCerNumber(), cerUtilsVos.get(i).getNumPeriods(), cerUtilsVos.get(i).getTrainingNumber(),
                            cerUtilsVos.get(i).getTraYear(), cerUtilsVos.get(i).getTraMath(), cerUtilsVos.get(i).getTraDay(), cerUtilsVos.get(i).getCerYear(), cerUtilsVos.get(i).getCerMath(),
                            cerUtilsVos.get(i).getCerDay(), cerUtilsVos.get(i).getElectronicSeal(),cerUtilsVos.get(i).getWorkUnit());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            //转换一下图片路径，将反斜杠替换掉
            String url = cerImgUrl.replace(ValuesUtil.localUrl, ValuesUtil.returnUrl);
            String imgUrl1 = url.replace("\\", "/");
            traCerDOList.get(i).setImgUrl(imgUrl1);//证书图片
            if (cerUtilsVos.get(i).getType() == 0) {
                //转换一下图片路径，将反斜杠替换掉
                String url1 = cerImgUrlNoSale.replace(ValuesUtil.localUrl, ValuesUtil.returnUrl);
                String imgUrl2 = url1.replace("\\", "/");
                traCerDOList.get(i).setImgUrlNosale(imgUrl2);//不带电子公章的证书图片链接
            }

        }

        trainingCertificatesService.updateBatchById(traCerDOList,traCerDOList.size());
    }

    //产后恢复
    @Async
    public void doTask12(List<CerUtilsVo> cerUtilsVos, List<TrainingCertificatesDO> traCerDOList){
        // 实现run方法
        for (int i = 0; i < cerUtilsVos.size(); i++) {
            //证书图片
            String cerImgUrl = null;
            String cerImgUrlNoSale = null;
            if (cerUtilsVos.get(i).getType() == 0) {
                try {
                    //参数说明：合成类型（0带公章，1不带公章），背景图，学员姓名，学员图像， 身份证号码，证书编码，考核期数，培训章节数（学时），培训年份，培训月份，培训日期，获证年份，获证年份，获证年份，电子公章
                    cerImgUrl = CerSynthesisUtil.overTrainingImageRecovery(0, cerUtilsVos.get(i).getBackgroundPath(), cerUtilsVos.get(i).getStuName(), cerUtilsVos.get(i).getStuImg(),
                            cerUtilsVos.get(i).getIdCard(), cerUtilsVos.get(i).getCerNumber(), cerUtilsVos.get(i).getNumPeriods(), cerUtilsVos.get(i).getTrainingNumber(),
                            cerUtilsVos.get(i).getTraYear(), cerUtilsVos.get(i).getTraMath(), cerUtilsVos.get(i).getTraDay(), cerUtilsVos.get(i).getCerYear(), cerUtilsVos.get(i).getCerMath(),
                            cerUtilsVos.get(i).getCerDay(), cerUtilsVos.get(i).getElectronicSeal(),cerUtilsVos.get(i).getWorkUnit(),cerUtilsVos.get(i).getGrade());
                    cerImgUrlNoSale = CerSynthesisUtil.overTrainingImageRecovery(1, cerUtilsVos.get(i).getBackgroundPath(), cerUtilsVos.get(i).getStuName(), cerUtilsVos.get(i).getStuImg(),
                            cerUtilsVos.get(i).getIdCard(), cerUtilsVos.get(i).getCerNumber(), cerUtilsVos.get(i).getNumPeriods(), cerUtilsVos.get(i).getTrainingNumber(),
                            cerUtilsVos.get(i).getTraYear(), cerUtilsVos.get(i).getTraMath(), cerUtilsVos.get(i).getTraDay(), cerUtilsVos.get(i).getCerYear(), cerUtilsVos.get(i).getCerMath(),
                            cerUtilsVos.get(i).getCerDay(), cerUtilsVos.get(i).getElectronicSeal(),cerUtilsVos.get(i).getWorkUnit(),cerUtilsVos.get(i).getGrade());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (cerUtilsVos.get(i).getType() == 1) {
                try {
                    //考评员证书
                    //参数说明：背景图，学员姓名，学员图像， 身份证号码，证书编码，证书名称，有效日期
                    cerImgUrl = CerSynthesisUtil.overTraExaImageRecovery(cerUtilsVos.get(i).getBackgroundPath(), cerUtilsVos.get(i).getStuName(), cerUtilsVos.get(i).getStuImg(),
                            cerUtilsVos.get(i).getIdCard(), cerUtilsVos.get(i).getCerNumber(), cerUtilsVos.get(i).getEffectiveDate(),cerUtilsVos.get(i).getWorkUnit(),cerUtilsVos.get(i).getGrade());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }else if (cerUtilsVos.get(i).getType() == 2) {
                try {
                    //考务技术员证书
                    //参数说明：背景图，学员姓名，学员图像， 身份证号码，证书编码，证书名称，有效日期
                    cerImgUrl = CerSynthesisUtil.overTraExaAffImage(cerUtilsVos.get(i).getBackgroundPath(), cerUtilsVos.get(i).getStuName(), cerUtilsVos.get(i).getStuImg(),
                            cerUtilsVos.get(i).getIdCard(), cerUtilsVos.get(i).getCerNumber(), cerUtilsVos.get(i).getEffectiveDate(),cerUtilsVos.get(i).getWorkUnit());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }else if (cerUtilsVos.get(i).getType() == 3) {
                try {
                    //考务技术员-结业证书
                    //参数说明：合成类型（0带公章，1不带公章），背景图，学员姓名，学员图像， 身份证号码，证书编码，考核期数，培训章节数（学时），培训年份，培训月份，培训日期，获证年份，获证年份，获证年份，电子公章
                    cerImgUrl = CerSynthesisUtil.overTraAraGradiningImage(0, cerUtilsVos.get(i).getBackgroundPath(), cerUtilsVos.get(i).getStuName(), cerUtilsVos.get(i).getStuImg(),
                            cerUtilsVos.get(i).getIdCard(), cerUtilsVos.get(i).getCerNumber(), cerUtilsVos.get(i).getNumPeriods(), cerUtilsVos.get(i).getTrainingNumber(),
                            cerUtilsVos.get(i).getTraYear(), cerUtilsVos.get(i).getTraMath(), cerUtilsVos.get(i).getTraDay(), cerUtilsVos.get(i).getCerYear(), cerUtilsVos.get(i).getCerMath(),
                            cerUtilsVos.get(i).getCerDay(), cerUtilsVos.get(i).getElectronicSeal(),cerUtilsVos.get(i).getWorkUnit());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            else if (cerUtilsVos.get(i).getType() == 4) {
                try {
                    //督导员证
                    //参数说明：背景图，学员姓名，学员图像， 身份证号码，证书编码，证书名称，有效日期
                    cerImgUrl = CerSynthesisUtil.overTraSupervisorExaAffImage(cerUtilsVos.get(i).getBackgroundPath(), cerUtilsVos.get(i).getStuName(), cerUtilsVos.get(i).getStuImg(),
                            cerUtilsVos.get(i).getIdCard(), cerUtilsVos.get(i).getCerNumber(), cerUtilsVos.get(i).getEffectiveDate(),cerUtilsVos.get(i).getWorkUnit());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }else if (cerUtilsVos.get(i).getType() == 5) {
                try {
                    //督导员-结业证书
                    //参数说明：合成类型（0带公章，1不带公章），背景图，学员姓名，学员图像， 身份证号码，证书编码，考核期数，培训章节数（学时），培训年份，培训月份，培训日期，获证年份，获证年份，获证年份，电子公章
                    cerImgUrl = CerSynthesisUtil.overTraSupervisorGradiningImage(0, cerUtilsVos.get(i).getBackgroundPath(), cerUtilsVos.get(i).getStuName(), cerUtilsVos.get(i).getStuImg(),
                            cerUtilsVos.get(i).getIdCard(), cerUtilsVos.get(i).getCerNumber(), cerUtilsVos.get(i).getNumPeriods(), cerUtilsVos.get(i).getTrainingNumber(),
                            cerUtilsVos.get(i).getTraYear(), cerUtilsVos.get(i).getTraMath(), cerUtilsVos.get(i).getTraDay(), cerUtilsVos.get(i).getCerYear(), cerUtilsVos.get(i).getCerMath(),
                            cerUtilsVos.get(i).getCerDay(), cerUtilsVos.get(i).getElectronicSeal(),cerUtilsVos.get(i).getWorkUnit());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            //转换一下图片路径，将反斜杠替换掉
            String url = cerImgUrl.replace(ValuesUtil.localUrl, ValuesUtil.returnUrl);
            String imgUrl1 = url.replace("\\", "/");
            traCerDOList.get(i).setImgUrl(imgUrl1);//证书图片
            if (cerUtilsVos.get(i).getType() == 0) {
                //转换一下图片路径，将反斜杠替换掉
                String url1 = cerImgUrlNoSale.replace(ValuesUtil.localUrl, ValuesUtil.returnUrl);
                String imgUrl2 = url1.replace("\\", "/");
                traCerDOList.get(i).setImgUrlNosale(imgUrl2);//不带电子公章的证书图片链接
            }

        }

        trainingCertificatesService.updateBatchById(traCerDOList,traCerDOList.size());
    }

    @Async
    public void mk(Long examBatchId,String field){
        //获取考试批次
        ExaminationBatchDO examinationBatchDO = examinationBatchService.findOneByKv("id",examBatchId);
        //根据考试批次id对应的认证批次id,查询对应的所有考生信息
        List<StuSignUpComDO> stuSignUpDOS = stuSignUpService.findByKv("cbatch_id", examinationBatchDO.getId());

        if (stuSignUpDOS != null && stuSignUpDOS.size() > 0) {
            for (StuSignUpComDO stuSignUpDO : stuSignUpDOS) {
                double result = 0;

                ExaminationPaperDO examinationPaperDO = examinationPaperService.findOneByKv("ebatch_id", examinationBatchDO.getId(), "state", 99);
                //如果一个考生出现两套答卷只取其中一份答卷
                if(examinationPaperDO==null)return;
                List<ExaminationAnswerSheetComDO> examinationAnswerSheetDOs = examinationAnswerSheetService
                        .findByKv("stu_sign_id", stuSignUpDO.getId());
                ExaminationAnswerSheetComDO examinationAnswerSheetDO = null;
                //查询到考生对应的答卷

                if(examinationAnswerSheetDOs!=null && examinationAnswerSheetDOs.size()>0)
                    examinationAnswerSheetDO=examinationAnswerSheetDOs.get(0);
                List<Long> idss = examinationQuestionsService.selIdList(examinationPaperDO.getId());
                //试卷对应的试题，有试题才算分，没有直接0分处理；
                if(idss != null && idss.size()>0){
                    if (examinationAnswerSheetDO != null) {
                        //有答卷才算分，没有直接返回0
                        result = results(examinationAnswerSheetDO.getAnswerList(),idss);//考试总分

                    }
                }

                ExaminationResultsComDO examinationResultsDOss = examinationResultsService
                        .findOneByKv("cbatch_id", examinationBatchDO.getCbatchId(), "ebatch_id", examinationBatchDO.getId(), "stu_sign_id", stuSignUpDO.getId(),"field",field);
                if (examinationResultsDOss == null) {
                    ExaminationResultsComDO examinationResultsDO = new ExaminationResultsComDO();
                    examinationResultsDO.setCbatchId(examinationBatchDO.getCbatchId());//认证批次id
                    examinationResultsDO.setEbatchId(examinationPaperDO.getEbatchId());//考试批次id
                    examinationResultsDO.setStuSignId(stuSignUpDO.getId());//考生信息id
                    examinationResultsDO.setField(field);
                    examinationResultsDO.setNum2(stuSignUpDO.getNum2());
                    if(examinationAnswerSheetDO == null){
                        examinationResultsDO.setState(1);//缺考
                    }else{


                        examinationResultsDO.setState(0);//正常
                    }
                    examinationResultsDO.setTotalScore(result);//考试成绩

                    boolean b = examinationResultsService.insert(examinationResultsDO);
//                    if (!b) {
//                        return Result.fail("认证批次：" + stuSignUpDO.getCbatchId() + "，中的考试批次：" + examinationPaperDO.getEbatchId() + "，下的考生：" + stuSignUpDO.getName() + "的成绩录入失败！");
//                    } else {
                    if (examinationAnswerSheetDO != null) {
                        examinationAnswerSheetDO.setState(1);//改成已阅卷
                        boolean c = examinationAnswerSheetService.updateById(examinationAnswerSheetDO);
//                            if (!c) {
//                                return Result.fail("认证批次：" + stuSignUpDO.getCbatchId() + "，中的考试批次：" + examinationPaperDO.getEbatchId() + "，下的考生：" + stuSignUpDO.getName() + "答卷状态更改失败！");
//                            }
                    }

                    if (result >= examinationBatchDO.getPassMark()) {
                        stuSignUpDO.setState(6);//状态改为理论已过
                        boolean sbc = stuSignUpService.updateById(stuSignUpDO);
//                            if (!sbc) {
//                                return Result.fail("认证批次：" + stuSignUpDO.getCbatchId() + "，中的考试批次：" + examinationPaperDO.getEbatchId() + "，下的考生：" + stuSignUpDO.getName() + "的更新状态失败！");
//                            }
                    }

                    //  }
                }else {
                    if(examinationAnswerSheetDO == null){
                        examinationResultsDOss.setState(1);//缺考
                    }else{
                        examinationResultsDOss.setState(0);//正常
                    }
                    examinationResultsDOss.setTotalScore(result);//考试成绩
                    boolean b = examinationResultsService.updateById(examinationResultsDOss);
//                    if (!b) {
//                        return Result.fail("认证批次：" + stuSignUpDO.getCbatchId() + "，中的考试批次：" + examinationPaperDO.getEbatchId() + "，下的考生：" + stuSignUpDO.getName() + "的成绩录入失败！");
//                    } else {
                    if (examinationAnswerSheetDO != null) {
                        examinationAnswerSheetDO.setState(1);//改成已阅卷
                        boolean c = examinationAnswerSheetService.updateById(examinationAnswerSheetDO);
//                            if (!c) {
//                                return Result.fail("认证批次：" + stuSignUpDO.getCbatchId() + "，中的考试批次：" + examinationPaperDO.getEbatchId() + "，下的考生：" + stuSignUpDO.getName() + "答卷状态更改失败！");
//                            }
//                        }

                        if (result >= examinationBatchDO.getPassMark()) {
                            stuSignUpDO.setState(6);//状态改为理论已过
                            boolean sbc = stuSignUpService.updateById(stuSignUpDO);
//                            if (!sbc) {
//                                return Result.fail("认证批次：" + stuSignUpDO.getCbatchId() + "，中的考试批次：" + examinationPaperDO.getEbatchId() + "，下的考生：" + stuSignUpDO.getName() + "的更新状态失败！");
//                            }
                        }

                    }
                }

            }
        }
    }

    private double results(String answers,List<Long> idss) {
        double results = 0;
        if(StringUtils.isNotBlank(answers)){
            JSONArray jsonArray2 = JSONArray.fromObject(answers);
            for(int i = 0;i<jsonArray2.size();i++){
                if(idss.indexOf(Long.parseLong(jsonArray2.getJSONObject(i).getString("id"))) > -1){
                    ExaminationQuestionsDO examinationQuestionsDO = examinationQuestionsService.selectById(Long.parseLong(jsonArray2.getJSONObject(i).getString("id")));
                    if(!jsonArray2.getJSONObject(i).containsKey("value"))continue;
                    if (examinationQuestionsDO.getType() == 0 || examinationQuestionsDO.getType() == 2) {//单选题和判断题，答案唯一，可以不用拆解了
                        if (examinationQuestionsDO.getAnswers().equals(jsonArray2.getJSONObject(i).getString("value"))) {
                            results = results + examinationQuestionsDO.getScore();
                        }
                    } else if (examinationQuestionsDO.getType() == 1) {//多选题因为答案有多个，需要循环判断一下是否包含该答案
                        String[] ssb = jsonArray2.getJSONObject(i).getString("value").split(";;");
                        String answer = "";
                        for (int n = 0; n < ssb.length; n++) {
                            if (answer == "") {
                                answer = ssb[n];
                            } else {
                                answer = answer + ";;" + ssb[n];
                            }
                        }

                        if (examinationQuestionsDO.getAnswers().equals(answer)) {
                            results = results + examinationQuestionsDO.getScore();
                        }

                    }
                }
            }
        }

        return results;
    }

}
